package jjn.round1;

/**
 * @author Jjn
 * @since 2022/7/31 00:02
 */
public class LeetCode59_GenerateMatrixV2 {

    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];
        int left = 0, right = n - 1;
        int top = 0, bottom = n - 1;
        int cur = 0;
        while (left <= right) {
            while (top <= bottom) {
                // 纵坐标是top，从left -> right
                for (int i = left; i <= right; i++) {
                    result[top][i] = ++cur;
                }
                top++;
                // 横坐标是right，从top -> bottom
                for (int i = top; i <= bottom; i++) {
                    result[i][right] = ++cur;
                }
                right--;
                // 纵坐标是bottom，从right -> left
                for (int i = right; i >= left; i--) {
                    result[bottom][i] = ++cur;
                }
                bottom--;
                // 纵坐标是left，从bottom -> top
                for (int i = bottom; i >= top; i--) {
                    result[i][left] = ++ cur;
                }
                left++;
            }
        }
        return result;
    }
}
